package com.valsong.sandbox.mock;


import com.alibaba.jvm.sandbox.api.http.printer.ConcurrentLinkedQueuePrinter;
import com.alibaba.jvm.sandbox.api.http.printer.Printer;
import com.alibaba.jvm.sandbox.api.resource.ModuleEventWatcher;
import com.valsong.sandbox.mock.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 事件观察者上下文
 *
 * @author Val Song
 */
public interface EventWatcherContext {

    Logger log = LoggerFactory.getLogger(EventWatcherContext.class);


    /**
     * 初始化
     *
     * @param moduleEventWatcher 事件观察者
     * @param param              加载模块时传入的参数
     * @param printWriter        文本输出
     */
    default void initialize(ModuleEventWatcher moduleEventWatcher, Map<String, String> param, PrintWriter printWriter) {
        //准备
        this.prepare(moduleEventWatcher, param);
        final Printer printer = new ConcurrentLinkedQueuePrinter(printWriter);

        //注册Mockers
        List<MockConfig> mockConfigs = this.register();
        if (mockConfigs == null || mockConfigs.isEmpty()) {
            log.error("Mocker register failed! mockConfigs is empty!");
            printer.println("Mocker register failed! mockConfigs is empty!");
            return;
        }

        String mockConfigJson = JsonUtils.toPrettyJson(mockConfigs);

        log.info("mockConfigs:[{}]", mockConfigJson);
        log.info("Mocker register complete!");

        printer.println("mockConfigs:");
        printer.println(mockConfigJson);
        printer.println("Mocker register complete!");

        printer.waitingForBroken(2, TimeUnit.SECONDS);
        printer.close();

    }

    /**
     * 准备
     *
     * @param moduleEventWatcher 模块时间观察者
     * @param param              加载模块时传入的参数
     */
    void prepare(ModuleEventWatcher moduleEventWatcher, Map<String, String> param);

    /**
     * 注册
     *
     * @return mock方法匹配规则
     */
    List<MockConfig> register();
}
